<template>
  <div>
    <el-card>
      <el-form
        :inline="true"
        :model="searchForm"
        class="demo-form-inline"
        label-position="right"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="名称">
              <el-input
                v-model="searchForm.filename"
                placeholder="请输入名称"
                clearable
                :style="selectWidth"
                value-on-clear="null"
                @clear="searchForm.filename = null"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布者">
              <el-input
                v-model="searchForm.username"
                placeholder="请输入发布者"
                clearable
                :style="selectWidth"
                @clear="searchForm.username = null"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="类型">
              <el-select
                v-model="searchForm.type"
                placeholder="请选择类型"
                clearable
                :style="selectWidth"
                @clear="searchForm.type = null"
              >
                <el-option label="图片" value="图片" />
                <el-option label="视频" value="视频" />
                <el-option label="音频" value="音频" />
                <el-option label="文档" value="文档" />
                <el-option label="表格" value="表格" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="日期">
              <el-date-picker
                type="date"
                v-model="searchForm.create_date"
                placeholder="请选择日期"
                clearable
                :style="selectWidth"
                style="width: 200px"
                @clear="searchForm.create_date = null"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="buttons">
          <el-col>
            <el-form-item>
              <el-button type="primary" @click="onSearch"
                ><el-icon><Search /></el-icon>搜 索</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="" @click="onResetSearchForm"
                ><el-icon><Refresh /></el-icon>重 置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 表格部分 -->
    <el-card style="margin-top: 10px">
      <div style="margin-bottom: 5px">
        <el-button type="primary" plain size="small" @click="onAdd"
          ><el-icon><DocumentAdd /></el-icon>添加</el-button
        >
        <el-button
          type="danger"
          plain
          size="small"
          :disabled="multiple"
          @click="deleteMultiple"
          ><el-icon><DeleteFilled /></el-icon>删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        :element-loading-text="loadingText"
      >
        <el-table-column type="selection" :selectable="selectable" width="50" />
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template></el-table-column
        >
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="username" label="发布者" />
        <el-table-column prop="suffix" label="类型">
          <template #default="{ row }">
            <span
              v-if="
                row.suffix === 'jpg' ||
                row.suffix === 'png' ||
                row.suffix === 'jpeg'
              "
              >图片</span
            >
            <span v-if="row.suffix === 'mp4'">视频</span>
            <span v-if="row.suffix === 'mp3'">音频</span>
            <span v-if="row.suffix === 'doc' || row.suffix === 'docx'"
              >文档</span
            >
            <span v-if="row.suffix === 'xls' || row.suffix === 'xlsx'"
              >表格</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="time"
          label="时间"
          sortable
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            {{ dayjs(row.create_date).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作选项" width="180">
          <template #default="{ row }">
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onDownload(row)"
              ><el-icon><Download /></el-icon>下载</el-button
            >
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onRevocation(row)"
              ><el-icon><Delete /></el-icon>删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 弹窗部分 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="onReset(addRuleFormRef)"
      width="40%"
    >
      <el-form
        ref="addRuleFormRef"
        style="max-width: 450px"
        :model="addRuleForm"
        :rules="addRules"
        label-width="80"
        class="demo-ruleForm"
        status-icon
        @submit.prevent
      >
        <el-form-item label="名称" prop="name" name="name" required>
          <el-input
            v-model="addRuleForm.name"
            placeholder="请输入名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="上传文件" prop="fileList" name="fileList">
          <el-tabs
            type="border-card"
            @tab-click="handleTabClick"
            v-model="activeName"
          >
            <el-tab-pane
              v-for="item in tabPane"
              :key="item.name"
              :label="item.label"
              :name="item.name"
            >
              <el-upload
                v-model:file-list="addRuleForm.fileList"
                class="upload-demo"
                action="#"
                :accept="accept"
                :auto-upload="false"
                :limit="1"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="beforeUpload"
                :on-exceed="handleExceed"
              >
                <template #trigger>
                  <el-button type="primary">选择文件</el-button>
                </template>
              </el-upload>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onReset(addRuleFormRef)">取 消</el-button>
          <el-button type="primary" @click="onSubmit(addRuleFormRef)"
            >提 交</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script  setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import {
  getMultimediaList,
  getFilesByCondition,
  deleteFiles,
  uploadFiles,
  downloadFile
} from '@/api/multimedia/multimediaList.js'

const store = useStore()
const userId = store.state.app.user.id
const ids = ref([])
const multiple = ref(true)
const selectable = (row) => ![1, 2].includes(row.id)
const addDialogVisible = ref(false)
const addRuleFormRef = ref()
const total = ref(0)
const title = ref('添加')
const activeName = ref('picture')
const selectWidth = ref('width:200px')
const propsName = ref('picture')
const loading = ref(false)
const tabPane = ref([
  {
    label: '图片',
    name: 'picture'
  },
  {
    label: '视频',
    name: 'video'
  },
  {
    label: '音频',
    name: 'audio'
  },
  {
    label: 'Word',
    name: 'word'
  },
  {
    label: 'Excel',
    name: 'excel'
  }
])
const accept = ref()
const loadingText = ref('')
// 添加表单的内容
const addRuleForm = ref({
  name: '',
  username: '',
  fileList: []
})
// 搜索框
const searchForm = ref({
  filename: null,
  username: null,
  type: null,
  create_date: null
})
const tableData = ref([])

// 校验规则
const addRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})

watch(
  () => propsName.value,
  (newValue) => {
    if (newValue === 'picture') {
      accept.value = '.jpg,.png,.jpeg'
    } else if (newValue === 'video') {
      accept.value = '.mp4'
    } else if (newValue === 'audio') {
      accept.value = '.mp3'
    } else if (newValue === 'word') {
      accept.value = '.doc,.docx'
    } else if (newValue === 'excel') {
      accept.value = '.xls,.xlsx'
    }
  },
  { immediate: true }
)

watch(
  () => searchForm.value,
  (newValue) => {
    if (newValue.filename === '') {
      searchForm.value.filename = null
    }
    if (newValue.username === '') {
      searchForm.value.username = null
    }
    if (newValue.create_date === '') {
      searchForm.value.create_date = null
    }
    if (newValue.type === '') {
      searchForm.value.type = null
    }
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  getList()
})

const getList = async () => {
  loading.value = true
  loadingText.value = '数据加载中...'
  await getMultimediaList({
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  })
    .then((res) => {
      tableData.value = res.data.list
      total.value = res.data.total
      loading.value = false
      loadingText.value = ''
    })
    .catch((err) => {
      console.log(err)
      loading.value = false
      loadingText.value = ''
    })
}
// 搜索
const onSearch = async () => {
  const searchDate = searchForm.value.create_date
    ? dayjs(searchForm.value.create_date).format('YYYY-MM-DD')
    : null
  await getFilesByCondition({
    ...queryParams.value,
    ...searchForm.value,
    create_date: searchDate
  })
    .then((res) => {
      if (res.data === null) {
        total.value = 0
        tableData.value = []
      }
      total.value = res.data.total
      tableData.value = res.data.list
    })
    .catch((err) => {
      console.log(err)
    })
}

// 重置表单
const onResetSearchForm = () => {
  searchForm.value = {
    filename: null,
    username: null,
    type: null,
    create_date: null
  }
  getList()
}

// 增加
const onAdd = () => {
  title.value = '添加'
  activeName.value = 'picture'
  addDialogVisible.value = true
}
// 下载文件
const onDownload = async (row) => {
  try {
    const response = await downloadFile(row.uuid)
    // 确保 response 和 response.data 存在
    if (!response || !response.data) {
      throw new Error('No data received from server')
    }

    // 创建 Blob 对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/octet-stream'
    })

    // 尝试从 Content-Disposition 中获取文件名
    let filename = null
    if (response.headers['content-disposition']) {
      try {
        // 使用正则表达式安全地解析文件名
        const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(
          response.headers['content-disposition']
        )
        if (match && match[1]) {
          filename = decodeURIComponent(match[1].trim().replace(/['"]/g, '')) // 移除引号并解码URL编码字符
        }
      } catch (error) {
        console.warn(
          'Failed to parse filename from Content-Disposition header:',
          error
        )
      }
    }

    // 如果没有成功获取文件名，则使用默认文件名
    if (!filename) {
      filename = `${row.name}.zip` // 更具描述性的默认文件名
    }

    // 创建一个临时的 <a> 元素用于下载
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename

    // 将 <a> 元素添加到 DOM 中并触发点击事件
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // 释放 Blob URL 资源
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    // console.error('Download failed:', error.message || error)
  }
  await downloadFile(row.uuid)
    .then((res) => {
      console.log(res)
    })
    .catch((err) => {
      console.log(err)
    })
}
// 删除一条
const onRevocation = (row) => {
  ElMessageBox.confirm('您确定要删除这条数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteFiles([row.uuid])
        .then((res) => {
          ElMessage({
            type: 'success',
            message: res.message
          })
          getList()
        })
        .catch((err) => {
          console.log(err)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 删除多条
const deleteMultiple = () => {
  ElMessageBox.confirm('您确定要删除这几条数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteFiles(ids.value)
        .then((res) => {
          ElMessage({
            type: 'success',
            message: res.message
          })
          getList()
        })
        .catch((err) => {
          console.log(err)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 切换tab
const handleTabClick = (tab, event) => {
  propsName.value = tab.props.name
}
// 文件预览
const handlePreview = (uploadFile) => {
  console.log('uploadFile', uploadFile)
}
// 文件删除
const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const beforeUpload = (file) => {
  const typeArray = accept.value.split(',') || []
  const type = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
  console.log(type)
  addRuleForm.value.fileList.push(file)
  if (!typeArray.includes(type)) {
    ElMessage.error(`只能上传${accept.value}格式的文件`)
    addRuleForm.value.fileList = []
    return false
  }
  if (file.size / 1024 / 1024 > 500) {
    ElMessage.error('文件大小不能超过500M')
    addRuleForm.value.fileList = []
    return false
  }
}

// 文件超出限制时触发
const handleExceed = (files, fileList) => {
  addRuleForm.value.fileList = [files[0]]
}

// 提交
const onSubmit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (addRuleForm.value.fileList.length === 0) {
        return ElMessage.error('请选择文件')
      }
      const formData = new FormData()
      addRuleForm.value.fileList.forEach(async (file) => {
        if (file.raw) {
          formData.append('file', file.raw)
          formData.append('filename', addRuleForm.value.name)
          formData.append('userId', userId)
        }
        loading.value = true
        loadingText.value = '上传中，请稍后...'
        addDialogVisible.value = false
        await uploadFiles(formData).then(async (res) => {
          if (res.success) {
            ElMessage.success(res.message)
            addRuleForm.value.fileList = []
            await getList()
            loading.value = false
            loadingText.value = ''
          } else {
            ElMessage.error(res.message)
            loading.value = false
            loadingText.value = ''
          }
        })
      })
    } else {
      console.log('error submit!', fields)
      loading.value = false
      loadingText.value = ''
    }
  })
}
// 重置
const onReset = (formEl) => {
  addRuleForm.value = {
    name: '',
    username: '',
    fileList: []
  }
  formEl.resetFields()
  addDialogVisible.value = false
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.uuid)
  multiple.value = !selection.length
}
</script>

<style lang="scss" scoped>
:deep(.el-table .el-table__header-wrapper th) {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px !important;
  font-size: 13px;
}

:deep(.el-form .el-form-item .el-form-item__label) {
  font-weight: bold !important;
}

:deep(.el-form .el-form-item .second_label .el-form-item__label) {
  font-weight: bold !important;
}
:deep(.second_label .el-form-item__error) {
  position: static !important;
}
.buttons {
  text-align: center;
}
</style>
